package com.njqy.ticket.service.common.impl;

import com.njqy.ticket.dto.common.LoginUser;
import com.njqy.ticket.service.common.ILoginService;
import com.njqy.ticket.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private AuthenticationManager authenticationManager;


    @Override
    public String login(String username, String password) {
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            throw new RuntimeException("用户名、密码不能为空");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证不通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名密码认证失败");
        }
        //认证通过
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String token = JwtUtils.createToken(loginUser);
        return token;
    }
}
